import {plcEvents} from '@/services/plc_service'

import {saveChartData} from '@/api/chartData';
import {getConfig} from '@/mapper/config-store'; // 导入图表数据API
let baseAddressMap = {}

let key_station_map = {
    "dc_8070": "station1"
}

let address_key_list = []

export async function startChartDataService() {
    try {
        await initAddress()
    } catch (e) {
        console.log('初始化地址报错:', e.message)
    }

    plcEvents.on('dc-value-changed', (eventData) => {
        try {
            let {key, value, values, addresses} = eventData
            processDcValueChange(key, value, values, addresses)
        } catch (e) {
            console.log('dc-value-changed 报错:', e.message)
        }
    })
}

async function processDcValueChange(key, value, values, addresses) {
    let station = key_station_map[key]
    let sn = values[`${station}_scanData`]
    let dataValues = {}
    address_key_list.forEach(key => {
        let address = baseAddressMap[key]
        dataValues[address.propertyName] = values[key]
    })
    saveChartData(sn, dataValues)
}


async function initAddress() {
    let addresses = await getConfig('plcAddresses')
    key_station_map = {}
    addresses.forEach(address => {
        let addr = parseInt(address.address.replace(/[A-Za-z]/g, ''))
        let key = `dc_${addr}`
        key_station_map[key] = address.station
        address_key_list.push(key)
        baseAddressMap[key] = {
            key: key,
            propertyName: address.propertyName,
            station: address.station,
            address: parseInt(address.address.replace(/[A-Za-z]/g, '')),
            type: address.type,
            length: 2,
            description: address.description
        }
    })
}
